#!/bin/env python3
#coding=utf-8
from lib.bottle import route, request, response
from lib.tools import User, Tools
from lib.catch import Session
from urllib import parse
import base64


@route('/api/login-manager/register', method='POST')
def sugar_register():
    tools = Tools()
    # ip filter
    if not tools.ipfilter(request.environ.get('REMOTE_ADDR')):
        return {
            'code': '-6',
            'message': '触发注册接口限制，请稍后再试～'
        }

    # nomal part
    cookietime = 3600
    data = request.POST.decode('utf-8')
    nick = data.get('nickname', None)  # nick name
    pwd = data.get('pwd', None)  # password
    active = data.get('active', None)  # active name
    activeid = data.get('activeid', None)  # active id
    coverid = request.get_cookie('Coverid')  # coverid
    token = request.get_cookie('Token')  # token

    # filters
    session = Session(activeid, token) # 开启session
    if coverid is None:
        return {
            'code': '-5',
            'message': '链接已过期，请刷新页面再试'
        }

    if session.gets("Coverid") != coverid:
        return {
            'code': '-6',
            # 'message': '链接超时，请刷新页面再试～'
            'message': str(session.gets("Coverid")) + str(coverid)
        }

    if nick is None:
        return {
            'code': '-1',
            'message': '昵称不能为空哦～'
        }
    if not tools.checkWords(pwd, '^[a-zA-Z0-9_+&]+$'):
        return {
            'code': '-2',
            'message': '密码格式不正确～'
        }

    # regist with database
    userobj = User(nick)
    if userobj.repeat():
        return {
            'code': '-3',
            'message': '用户名重复了哦～'
        }
    if not userobj.register(pwd):
        return {
            'code' : '-4',
            'message' : '系统繁忙，请稍后再试～'
        }

    # result and set cookies
    res = {}
    # 重置 Coverid
    coverid = tools.get_coverid()
    tools.setcookie("Coverid", coverid, tools.covertime)
    session.save({"Coverid" : coverid})

    tools.setcookie("Active", active, cookietime)
    tools.setcookie("Activeid", activeid, cookietime)
    tools.setcookie("Token", session.token, cookietime)
    res['nickname'] = nick
    res['code'] = 200
    res['message'] = '注册成功！'
    return res


@route('/api/login-manager/login', method='POST')
def sugar_login():
    """
        LoginManager 请求接口，检测检测用户名密码，并载入session
    """
    tools = Tools()
    # ip filter
    if not tools.ipfilter(request.environ.get('REMOTE_ADDR')):
        return {
            'code': '-6',
            'message': '触发接口限制，请稍后再试～'
        }

    # nomal part
    cookietime = 3600
    data = request.POST.decode('utf-8')
    nick = data.get('nickname', None)  # nick name
    pwd = data.get('pwd', None)  # password
    active = data.get('active', None)  # active name
    activeid = data.get('activeid', None)  # active id
    coverid = request.get_cookie('Coverid')  # coverid
    token = request.get_cookie('Token')  # token

    # session set
    session = Session(activeid, token)

    # filters
    if coverid is None:
        return {
            'code': '-5',
            'message': '链接已过期，请刷新页面再试5~'
        }
    if session.gets("Coverid") != coverid:
        return {
            'code': '-6',
            'message': "链接已过期，请刷新页面再试6~"
        }
    if nick is None:
        return {
            'code': '-1',
            'message': '昵称不能为空哦～'
        }
    if not tools.checkWords(pwd, '^[a-zA-Z0-9_+&]+$'):
        return {
            'code': '-2',
            'message': '密码格式不正确～'
        }

    # login
    userobj = User(nick)
    if not userobj.checklogin(pwd):
        return {
            'code' : '-4',
            'message' : '用户名或密码错误～'
        }

    # result and set cookies
    res = {}
    coverid = tools.get_coverid()
    tools.setcookie("Coverid", coverid, tools.covertime)
    session.save({"Coverid" : coverid})

    tools.setcookie("Active", active, cookietime)
    tools.setcookie("Nickname", parse.quote_plus(userobj.unitdata[3]), cookietime)
    tools.setcookie("Activeid", activeid, cookietime)
    res['nickname'] = nick
    res['code'] = 200
    res['message'] = '登陆成功～'
    tools.setcookie("Token", session.token, cookietime)
    tools.setcookie("Unitid", userobj.unitdata[1], cookietime)
    return res


@route('/api/login-manager/leave', method='GET')
def sugar_leave():
    data = request.GET.decode('utf-8')
    coverid = request.get_cookie('Coverid')  # coverid
    activeid = data.get('activeid', None)  # active id
    token = request.get_cookie('Token')  # token
    # session set
    session = Session(activeid, token)
    # filters
    if coverid is None:
        return {
            'code': '-5',
            'message': '链接已过期，请刷新页面再试1~'
        }
    if session.gets("Coverid") != coverid:
        return {
            'code': '-6',
            'message': "链接已过期，请刷新页面再试2~"
        }
    tools = Tools()
    tools.setcookie("Coverid", '', -1)
    tools.setcookie("Nickname", '', -1)
    tools.setcookie("Token", '', -1)
    tools.setcookie("Unitid", '', -1)
    tools.setcookie("Active", '', -1)
    tools.setcookie("Activeid", '', -1)
    return {
        'code' : 200,
        'message': '注销成功～'
    }


@route('/api/login-manager/getcoverid', method='GET')
def sugar_getcoverid():
    tools = Tools()
    data = request.GET.decode('utf-8')
    actid = data.get("activeid", None)
    unitid = tools.getcookie("Unitid")
    session = Session(actid, unitid)
    if tools.getcookie("Coverid") is None:
        coverid = tools.get_coverid()
        session.save({"Coverid" : coverid})
        tools.setcookie("Coverid", coverid, tools.covertime)

    if tools.getcookie("Token") is None:
        token = str(session.gets("_id"))
        tools.setcookie("Token", token, tools.covertime)
    return "var covertime = " + str(tools.covertime) + ";"
